//
//  YSTabBar.m
//  YiShi
//
//  Created by myMac on 15/7/3.
//  Copyright (c) 2015年 myMac. All rights reserved.
//

#import "YSTabBar.h"
#import "YSTabButton.h"

@implementation YSTabBar

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (instancetype)init {
    if (self = [super init]) {
        
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
    }
    return self;
}

- (void)setItems:(NSArray *)items {
    _items = [items copy];
    for (int i = 0; i < items.count; i++) {
        YSTabButton *tabButton = [items objectAtIndex:i];
        tabButton.tag = 100 + i;
        [self addSubview:tabButton];
        [tabButton addTarget:self
                      action:@selector(tabAction:)
            forControlEvents:UIControlEventTouchUpInside];
    }
    [self layoutSubviews];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    if (self.items.count == 0) {
        return;
    }
    CGFloat itemWidth = self.bounds.size.width / self.items.count;
    CGFloat itemHeight = self.bounds.size.height;
    for (int i = 0; i < self.items.count; i++) {
        YSTabButton *tabButton = [self.items objectAtIndex:i];
        tabButton.frame = CGRectMake(itemWidth * i, 0, itemWidth, itemHeight);
        tabButton.selected = i == self.selectedIndex;
    }
}

- (void)tabAction:(YSTabButton *)sender {
    NSInteger selectIndex = sender.tag - 100;
    if (selectIndex != self.selectedIndex) {
        self.selectedIndex = selectIndex;
        for (int i = 0; i < self.items.count; i++) {
            YSTabButton *tabButton = [self.items objectAtIndex:i];
            tabButton.selected = i == selectIndex;
        }
    }
}

- (void)setSelectedIndex:(NSInteger)selectedIndex {
    _selectedIndex = selectedIndex;
    if ([self.delegate respondsToSelector:@selector(YSTabBar:didSelectedIndex:)]) {
        [self.delegate YSTabBar:self didSelectedIndex:self.selectedIndex];
    }
}

#pragma private methods
- (void)setupSeparatorView {
    UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 1.0)];
    separatorView.backgroundColor = [UIColor lightGrayColor];
    [self addSubview:separatorView];
    separatorView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
}

@end
